import { useMemo } from "react";
import { useMutation, useQuery, useQueryClient } from "react-query";

import { ArticleType } from "types/article";
import { useHttp } from "utils/http";
import { useUrlQueryParam } from "utils/url";

export const useArticleSearchParams = () => {
  const [param, setParam] = useUrlQueryParam([
    "title",
    "status",
    "page",
    "limit",
  ]);
  return [
    useMemo(
      () => ({
        ...param,
        status: Number(param.status) || undefined,
      }),
      [param]
    ),
    setParam,
  ] as const;
};

interface returnData {
  total: number;
  lists: ArticleType[];
}
export const useArticles = (param?: Partial<ArticleType>) => {
  const client = useHttp();

  return useQuery<returnData>(["articles", param], () =>
    client("article/lists", { data: param })
  );
};

export const useAddArticle = () => {
  const client = useHttp();
  const queryClient = useQueryClient();
  return useMutation(
    (params: Partial<ArticleType>) =>
      client(`article/add`, { data: params, method: "POST" }),
    {
      onSuccess: () => {
        queryClient.invalidateQueries();
      },
    }
  );
};

export const useArticleParam = () => {
  const [{ id }] = useUrlQueryParam(["id"]);
  const { data: article, isLoading } = useArticle(Number(id));

  return {
    id,
    article,
    isLoading,
  };
};

export const useArticle = (id?: number) => {
  const client = useHttp();
  return useQuery<ArticleType>(
    ["article", { id }],
    () => client(`article/detail/${id}`),
    {
      enabled: !!id,
    }
  );
};

export const useArticleDel = (param?: Partial<ArticleType>) => {
  const client = useHttp();
  const queryClient = useQueryClient();
  return useMutation(
    (params: Partial<ArticleType>) =>
      client(`article/del`, {
        data: params,
        method: "POST",
      }),
    {
      onSuccess: () => {
        queryClient.invalidateQueries();
      },
    }
  );
};

export const useModifyArticle = () => {
  const client = useHttp();
  const queryClient = useQueryClient();
  return useMutation(
    (params: Partial<ArticleType>) =>
      client(`article/modify`, {
        data: params,
        method: "POST",
      }),
    {
      onSuccess: () => {
        queryClient.invalidateQueries();
      },
    }
  );
};
